package com.googlecode.aleverr.yafotkiclient.api;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class FormDataGenerator {

    public static final String BOUNDARY = "frekgh738gGHUehfui33qqQ";
    
    private static final int BUFFER_SIZE = 10240;

    private static abstract class Section {
        public abstract void write(OutputStream out) throws IOException;
    }

    private static class TextSection extends Section {

        private final String name;
        private final String value;

        private TextSection(String name, String value) {
            this.name = name;
            this.value = value;
        }

        @Override
        public void write(OutputStream out) throws IOException {
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out));
            writer.write("--" + BOUNDARY + "\r\n");
            writer.write("Content-Disposition: form-data; name=\"" + name + "\"\r\n\r\n");
            writer.write(value + "\r\n");
            writer.flush();
        }
    }

    private static class JpegSection extends Section {

        private String name;
        private String filePath;

        public JpegSection(String name, String filePath) {
            this.name = name;
            this.filePath = filePath;
        }

        @Override
        public void write(OutputStream out) throws IOException {
            File file = new File(filePath);

            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out));
            writer.write("--" + BOUNDARY + "\r\n");
            writer.write("Content-Disposition: form-data; name=\"" + name + "\"; filename=\"" + file.getName() + "\"\r\n");
            writer.write("Content-Type: image/jpeg\r\n");
            writer.write("Content-Length: " + file.length() + "\r\n\r\n");
            writer.flush();

            InputStream in = new FileInputStream(file);
            byte[] buffer = new byte[BUFFER_SIZE];
            while (in.read(buffer) != -1) {
                out.write(buffer);
            }
            in.close();
            out.flush();
            writer.write("\r\n");
            writer.flush();
        }
    }

    private final List<Section> sections = new ArrayList<Section>();

    public void addTextSection(String name, String value) {
        sections.add(new TextSection(name, value));
    }

    public void addJpegSection(String name, String filePath) {
        sections.add(new JpegSection(name, filePath));
    }

    public void write(OutputStream out) throws IOException {
        for (Section section : sections) {
            section.write(out);
        }
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out));
        writer.write("--" + BOUNDARY + "\r\n");
        writer.flush();
    }
}
